/*
 * Copyright 2009-2010 the original author or authors.
 *
 * Licensed under the Apache license, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.internna.iwebjtracker.i18n;

import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.internna.iwebjtracker.project.validation.Errors;

import static org.internna.iwebmvc.utils.StringUtils.hasText;
import static org.internna.iwebmvc.spring.i18n.WebContextLocale.getActiveLocale;

/**
 * Allows subclasses to resolve messages
 *
 * @author Jose Noheda
 * @since 1.0
 */
public abstract class MessageResolver {

    private final MessageSource messageSource;

    /**
     * Constructor injection point.
     *
     * @param messageSource any
     */
    protected MessageResolver(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    /**
     * Delegates to resolve(string) providing a string representation of this error.
     *
     * @param error any
     * @return any
     */
    protected final String resolve(Errors error) {
        String resolve = error == null ? null : error.toString();
        return resolve(resolve);
    }

    /**
     * If a valid configured resolver is present it tries to obtain the i18n message. If anything fails or
     * no resolver is available it returns the provided input untouched.
     *
     * @param error
     * @return
     */
    protected final String resolve(String resolve) {
        try {
            return messageSource != null && hasText(resolve) ? messageSource.getMessage(resolve, null, getCurrentLocale()) : resolve;
        } catch (NoSuchMessageException ex) {
            return resolve;
        }
    }

    /**
     * Defaults to the request locale. In test environments (or other non web contexts) falls back to Locale.ENGLISH.
     *
     * @return ENGLISH unless other locale could be detected in the environment
     */
    protected final Locale getCurrentLocale() {
        try {
            return getActiveLocale();
        } catch (Exception ex) {
            return Locale.ENGLISH;
        }
    }

}
